import com.mt.components.consts.Exception;
import com.mt.components.consts.PermissionName;
import com.mt.components.consts.SysConst;
import com.mt.components.general.DataBox;
import com.mt.components.general.Node;
import com.mt.components.utils.AlertFactory;
import com.mt.components.utils.RemoteFactory;
import com.mt.components.utils.StringUtils;
import com.mt.system.domain.Permission;
import com.mt.system.domain.Role;

import flash.events.Event;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.events.FlexEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.mxml.RemoteObject;
import mx.utils.StringUtil;

/**      
 * 文件名称：SaveRoleAs.as<br>
 * 文件描述：<br>
 * 创建人：马腾<br>
 * 创建时间：Dec 8, 2012 1:42:20 PM<br>
 * 修改人：马腾<br>
 * 修改时间：Dec 8, 2012 1:42:20 PM<br>
 */

public var role:Role;
[Bindable]private var permissions:ArrayCollection;

override protected function init(event:FlexEvent):void{
	super.init(event);
	if(role){
		nameText.text = role.name;
		descText.text = role.desc;
		nameText.enabled = false;
		var remote:RemoteObject = RemoteFactory.getInstance().getRemote("PermissionService");
		remote.addEventListener(ResultEvent.RESULT , function (e:ResultEvent):void {
			role.permissions = e.result as ArrayCollection;
		});
		remote.getPermissionByRole(role);
	}
}

/**
 * 保存角色 
 */
protected function save():void {
	if(StringUtils.isEmpty(nameText.text)){
		mes.text = "用户名不能为空！";return;
	}
	if(StringUtils.isEmpty(descText.text)){
		mes.text = "请输入角色描述！";return;
	}
	var temp:Role = new Role();
	temp.name = StringUtil.trim(nameText.text);
	temp.isAdmin = false;
	temp.desc = StringUtil.trim(descText.text);
	var remote:RemoteObject;
	if(role){
		temp.id = role.id;
		temp.permissions = role.permissions;
		remote = RemoteFactory.getInstance().getRemote("RoleService" , PermissionName.ROLE_MOD);
		remote.updateRole(temp);
	}else{
		remote = RemoteFactory.getInstance().getRemote("RoleService" , PermissionName.ROLE_ADD);
		remote.addRole(temp);
	}
	remote.addEventListener(ResultEvent.RESULT , saveSuccess);
	remote.addEventListener(FaultEvent.FAULT , function (e:FaultEvent):void {
		if(e.message.toString().indexOf(Exception.FIND_REPATE_DATA) != -1){
			AlertFactory.getInstance().alert("该角色" + temp.name + "已经存在!");
		}
	});
}

protected function saveSuccess(event:ResultEvent):void {
	this.dispatchEvent(new Event(SysConst.SAVE_SUCCESS));
	super.close();
}